#!/bin/bash -xe

source $(dirname $0)/env.sh

sudo rm -rf $ROOTFS_DIR
mkdir -p $ROOTFS_DIR
ln -sf $MOUNT_TARGET $MOUNT_DIR

mkdir -p $ROOTFS_DIR/etc/init.d
mkdir -p $ROOTFS_DIR/proc
mkdir -p $ROOTFS_DIR/sys
mkdir -p $ROOTFS_DIR/tmp
mkdir -p $ROOTFS_DIR/root
mkdir -p $ROOTFS_DIR/var
mkdir -p $ROOTFS_DIR/mnt
mkdir -p $ROOTFS_DIR/home
mkdir -p $ROOTFS_DIR/lib
mkdir -p $ROOTFS_DIR/dev

cat > $ROOTFS_DIR/etc/fstab << EOF
#device     mount-point         type        options                     dump    fsck    order
proc        /proc               proc        defaults                    0       0
tmpfs       /tmp                tmpfs       defaults                    0       0
sysfs       /sys                sysfs       defaults                    0       0
tmpfs       /dev                tmpfs       defaults                    0       0
var         /dev                tmpfs       defaults                    0       0
ramfs       /dev                ramfs       defaults                    0       0
debugfs     /sys/kernel/debug   debugfs     defaults                    0       0
host_share  /mnt                9p          trans=virtio,msize=10485760 0       0
EOF

cat > $ROOTFS_DIR/etc/inittab << EOF
# /etc/inittab
::sysinit:/etc/init.d/rcS
console::askfirst:-/bin/bash
::ctrlaltdel:/sbin/reboot
::shutdown:/bin/umount -a -r
::restart:/sbin/init
EOF

cat > $ROOTFS_DIR/etc/init.d/rcS << EOF
#!/bin/sh
PATH=/sbin:/bin:/usr/sbin:/usr/bin
runlevel=S
prevlevel=N
umask 022
export PATH runlevel prevlevel
mount -a
mdev -s
EOF
chmod a+x $ROOTFS_DIR/etc/init.d/rcS

echo '#!/bin/sh
export HOSTNAME=qemu
export USER=root
export HOME=/root
export PS1="[$USER@$HOSTNAME \W]\# "
PATH=/bin:/sbin:/usr/bin:/usr/sbin
LD_LIBRARY_PATH=/lib:/usr/lib:$LD_LIBRARY_PATH
export PATH LD_LIBRARY_PATH' > $ROOTFS_DIR/etc/profile

sudo mknod $ROOTFS_DIR/dev/tty1 c 4 1
sudo mknod $ROOTFS_DIR/dev/tty2 c 4 2
sudo mknod $ROOTFS_DIR/dev/tty3 c 4 3
sudo mknod $ROOTFS_DIR/dev/tty4 c 4 4
sudo mknod $ROOTFS_DIR/dev/console c 5 1
sudo mknod $ROOTFS_DIR/dev/null c 1 3

cp -r $BUSYBOX_OUT_DIR/* $ROOTFS_DIR/
cp -r $BASH_OUT_DIR/* $ROOTFS_DIR/
cp -r /usr/$CONFIGURE_TOOLCHAIN/lib/* $ROOTFS_DIR/lib/
if [ -e /usr/$CONFIGURE_TOOLCHAIN/lib64 ]; then
    cp -r /usr/$CONFIGURE_TOOLCHAIN/lib64/* $ROOTFS_DIR/lib/
fi
ln -sf bash $ROOTFS_DIR/bin/sh

cd $ROOTFS_DIR
find | cpio -o -H newc | gzip > ../$ROOTFS_IMAGE
cd ..
